package com.boge.config;

import dev.langchain4j.community.store.embedding.redis.RedisEmbeddingStore;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.loader.ClassPathDocumentLoader;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class RagConfig {

    @Autowired
    private EmbeddingModel embeddingModel;

    @Autowired
    private RedisEmbeddingStore redisEmbeddingStore;

    /**
     *  构建向量数据操作的对象
     * @return
     */
    //@Bean
    public EmbeddingStore embeddingStore(){
        // 1. 加载文档到内存中
        List<Document> documents = ClassPathDocumentLoader.loadDocuments("content",new ApachePdfBoxDocumentParser());
        //List<Document> documents = FileSystemDocumentLoader.loadDocuments("H:\\workspace\\SpringAIWorkspace\\LangChain4j01Java\\LangChain4j02Spring\\LangChain4j02Spring\\src\\main\\resources\\content");
        // 2.构建向量数据库的操作对象
        //InMemoryEmbeddingStore store = new InMemoryEmbeddingStore();
        //DocumentSplitter splitter = DocumentSplitters.recursive(200, 50);
        // 3.构建一个EmbeddingStoreIngestor 会帮助我们完成文本数据的 切割 向量化 和 存储
        EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder()
                .embeddingStore(redisEmbeddingStore)
                .embeddingModel(embeddingModel)
                //.documentSplitter(splitter)
                .build();
        ingestor.ingest(documents);
        return redisEmbeddingStore;
    }

    /**
     * 向量数据库的检索
     * @param
     * @return
     */
    @Bean
    public ContentRetriever contentRetriever(/*EmbeddingStore store*/){
        return EmbeddingStoreContentRetriever.builder()
                .embeddingStore(redisEmbeddingStore)
                .embeddingModel(embeddingModel)
                .build();
    }

}
